package com.lh.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lh.entity.table.*;
import com.lh.entity.vo.TicketProblemPercentVo;
import com.lh.mapper.*;
import com.lh.service.ProblemSummaryInfoService;
import com.lh.utils.Answer;
import com.lh.utils.LogUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ProblemSummaryInfoServiceImpl implements ProblemSummaryInfoService {

    private LogUtil LOG = new LogUtil(ProblemSummaryInfoServiceImpl.class);

    @Autowired
    private ProblemSummaryInfoMapper problemSummaryInfoMapper;

    @Resource
    private TicketProblemPercentMapper ticketProblemPercentMapper;

    @Resource
    private TicketProblemInfoMapper ticketProblemInfoMapper;

    @Resource
    private TaskInfoMapper taskInfoMapper;

    @Resource
    private Task1InfoMapper task1InfoMapper;

    @Resource
    private Task2InfoMapper task2InfoMapper;

    @Override
    public Answer<Object> addProblemSummaryInfo(ProblemSummaryInfo problemSummaryInfo) {
        try {
            String projectName = problemSummaryInfo.getProjectName();
            if (StrUtil.isBlank(projectName)) {
                return Answer.error("项目名称不能为空");
            }
            List<ProblemSummaryInfo> existProblemSummaryInfoList = problemSummaryInfoMapper.selectList(new LambdaQueryWrapper<ProblemSummaryInfo>().eq(ProblemSummaryInfo::getProjectName, projectName));
            if (CollectionUtil.isNotEmpty(existProblemSummaryInfoList)) {
                return Answer.error("项目名称已存在");
            }
            List<ProblemSummaryInfo> problemSummaryInfos = problemSummaryInfoMapper.selectList(null);
            String formattedSequence = String.format("%02d", problemSummaryInfos.size()+1);
            problemSummaryInfo.setSummaryNo(DateUtil.format(new Date(), "yyMMdd") + formattedSequence);
            problemSummaryInfo.setCreatedTime(new Date());
            problemSummaryInfoMapper.insert(problemSummaryInfo);
            return Answer.ok(problemSummaryInfo.getId());
        } catch (Exception e) {
            e.printStackTrace();
            return LOG.error(Answer.build(), "请求addProblemSummaryInfo失败！", e);
        }
    }

    @Override
    public Answer<Object> updateProblemSummaryInfo(ProblemSummaryInfo problemSummaryInfo) {
        try {
            Integer id = problemSummaryInfo.getId();
            if (id == null) {
                return Answer.error("id不能为空");
            }
            ProblemSummaryInfo existProblemSummaryInfo = problemSummaryInfoMapper.selectById(id);
            if (existProblemSummaryInfo == null) {
                return Answer.error("突出问题不存在");
            }
            problemSummaryInfoMapper.updateById(problemSummaryInfo);
            return Answer.ok("请求成功");
        } catch (Exception e) {
            e.printStackTrace();
            return LOG.error(Answer.build(), "请求updateProblemSummaryInfo失败！", e);
        }
    }

    @Override
    public Answer<Object> deleteProblemSummaryInfo(ProblemSummaryInfo problemSummaryInfo) {
        try {
            Integer id = problemSummaryInfo.getId();
            if (id == null) {
                return Answer.error("id不能为空");
            }
            problemSummaryInfoMapper.deleteById(id);
            return Answer.ok("请求成功");
        } catch (Exception e) {
            e.printStackTrace();
            return LOG.error(Answer.build(), "请求deleteProblemSummaryInfo失败！", e);
        }
    }

    @Override
    public Answer<Object> selectProblemSummaryInfoPage(JSONObject reqJson) {
        try {
            DecimalFormat df = new DecimalFormat("0.00%");
            Integer pageSize = reqJson.getInteger("pageSize");
            Integer pageNum = reqJson.getInteger("pageNum");
//            PageHelper.startPage(pageNum, pageSize);
            Page<ProblemSummaryInfo> page = new Page<>(pageNum, pageSize);

//            ProblemSummaryInfo problemSummaryInfo = new ProblemSummaryInfo();
//            problemSummaryInfo.setProminentIssue(reqJson.getString("prominentIssue"));
//            problemSummaryInfo.setLeadUnit(reqJson.getString("leadUnit"));
//            problemSummaryInfo.setDataResource(reqJson.getString("dataResource"));
//            problemSummaryInfo.setStatus(reqJson.getString("status"));
            String prominentIssue = reqJson.getString("prominentIssue");
            String leadUnit = reqJson.getString("leadUnit");
            String dataResource = reqJson.getString("dataResource");
            String status = reqJson.getString("status");
            LambdaQueryWrapper<ProblemSummaryInfo> problemSummaryInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
            if (StrUtil.isNotBlank(prominentIssue)){
                problemSummaryInfoLambdaQueryWrapper.eq(ProblemSummaryInfo::getProminentIssue, prominentIssue);
            }
            if (StrUtil.isNotBlank(leadUnit)){
                problemSummaryInfoLambdaQueryWrapper.eq(ProblemSummaryInfo::getLeadUnit, leadUnit);
            }
            if (StrUtil.isNotBlank(dataResource)){
                problemSummaryInfoLambdaQueryWrapper.eq(ProblemSummaryInfo::getDataResource, dataResource);
            }
            if (StrUtil.isNotBlank(status)){
                problemSummaryInfoLambdaQueryWrapper.eq(ProblemSummaryInfo::getStatus, status);
            }
            problemSummaryInfoLambdaQueryWrapper.orderByDesc(ProblemSummaryInfo::getId);
            Page<ProblemSummaryInfo> problemSummaryInfoPage = problemSummaryInfoMapper.selectPage(page, problemSummaryInfoLambdaQueryWrapper);
            List<ProblemSummaryInfo> problemSummaryInfoList = problemSummaryInfoPage.getRecords();
            if(CollectionUtil.isNotEmpty(problemSummaryInfoList)){
                for (ProblemSummaryInfo summaryInfo : problemSummaryInfoList) {
                    List<Object> jsonDataList = CollectionUtil.newArrayList();
                    Integer id = summaryInfo.getId();
                    List<TicketProblemInfo> ticketProblemInfoList = ticketProblemInfoMapper.selectList(new LambdaQueryWrapper<TicketProblemInfo>().eq(TicketProblemInfo::getSummaryId, id));
                    if(CollectionUtil.isNotEmpty(ticketProblemInfoList)){
                        for (TicketProblemInfo ticketProblemInfo : ticketProblemInfoList) {
                            List<TicketProblemPercent> ticketProblemPercentList = ticketProblemPercentMapper.selectList(new LambdaQueryWrapper<TicketProblemPercent>().eq(TicketProblemPercent::getTicketProblemInfoId, ticketProblemInfo.getId()));
                            if(CollectionUtil.isNotEmpty(ticketProblemPercentList)){
                                List<TicketProblemPercentVo> ticketProblemPercentVoList = ticketProblemPercentList.stream().map(ticketProblemPercent -> {
                                    TicketProblemPercentVo ticketProblemPercentVo = new TicketProblemPercentVo();
                                    BeanUtils.copyProperties(ticketProblemPercent, ticketProblemPercentVo);
                                    return ticketProblemPercentVo;
                                }).collect(Collectors.toList());
                                ticketProblemInfo.setTicketProblemPercentVoList(ticketProblemPercentVoList);
                            }
                        }
                    }
                    List<String> issueTypeList = ticketProblemInfoList.stream().map(TicketProblemInfo::getIssueType).distinct().filter(StrUtil::isNotBlank).collect(Collectors.toList());
                    for (String issueType : issueTypeList) {
                        List<JSONObject> valueList = CollectionUtil.newArrayList();
                        JSONObject jsonObject = new JSONObject();
                        JSONObject jsonObject1 = new JSONObject();
                        JSONObject jsonObject2 = new JSONObject();
                        JSONObject jsonObject3 = new JSONObject();
                        jsonObject.put("issueType", issueType);
                        List<TicketProblemInfo> issueTypeTicketProblemInfoList = ticketProblemInfoList.stream().filter(ticketProblemInfo -> issueType.equals(ticketProblemInfo.getIssueType())).collect(Collectors.toList());
                        int field1 = issueTypeTicketProblemInfoList.size();
                        long field2 = issueTypeTicketProblemInfoList.stream().filter(ticketProblemInfo -> ticketProblemInfo.getStatus() != null && !ticketProblemInfo.getStatus().equals("1")).count();
                        jsonObject1.put("name", "任务数");
                        jsonObject1.put("value", field1);
                        jsonObject2.put("name", "销号数");
                        jsonObject2.put("value", Convert.toInt(field2));
                        jsonObject3.put("name", "占比");
                        jsonObject3.put("value", Convert.toInt(field1) == 0 ? "0.00%" : df.format((double) Convert.toInt(field2)  / Convert.toInt(field1)) );
                        valueList.add(jsonObject1);
                        valueList.add(jsonObject2);
                        valueList.add(jsonObject3);
                        jsonObject.put("value", valueList);
                        jsonDataList.add(jsonObject);
                    }
                    summaryInfo.setJsonDataList(jsonDataList);
                }

            }
            return Answer.ok(problemSummaryInfoList);
        } catch (Exception e) {
            e.printStackTrace();
            return LOG.error(Answer.build(), "请求selectProblemSummaryInfoPage失败！", e);
        }
    }

    @Override
    public Answer<Object> selectProblemSummaryInfoGroup(JSONObject reqJson) {
        try {
            DecimalFormat df = new DecimalFormat("0.00%");
            List<Object> resList = CollectionUtil.newArrayList();
            String group = reqJson.getString("group");

            List<ProblemSummaryInfo> problemSummaryInfoList = problemSummaryInfoMapper.selectList(null);
            List<String> leadUnitList = problemSummaryInfoList.stream().map(ProblemSummaryInfo::getLeadUnit).distinct().filter(StrUtil::isNotBlank).collect(Collectors.toList());
            if ("leadUnit".equals(group)){
                for (String leadUnit : leadUnitList) {
                    JSONObject json = new JSONObject();
                    List<ProblemSummaryInfo> collect = problemSummaryInfoList.stream().filter(problemSummaryInfo -> problemSummaryInfo.getLeadUnit() != null && problemSummaryInfo.getLeadUnit().equals(leadUnit)).collect(Collectors.toList());
                    int field1 = collect.size();
                    long field2 = collect.stream()
                            .filter(problemSummaryInfo -> problemSummaryInfo.getStatus() != null && problemSummaryInfo.getStatus().equals("已销号")).count();
                    json.put("leadUnit",leadUnit);
                    json.put("field1",field1);
                    json.put("field2", Convert.toInt(field2));
                    json.put("field3", Convert.toInt(field1-Convert.toInt(field2)));
                    json.put("proportion",Convert.toInt(field1) == 0 ? "0.00%" : df.format((double) Convert.toInt(field2)  / Convert.toInt(field1)));
                    resList.add(json);
                }
            }
            return Answer.ok(resList);
        } catch (Exception e) {
            e.printStackTrace();
            return LOG.error(Answer.build(), "请求selectProblemSummaryInfoGroup失败！", e);
        }
    }

    @Override
    public Answer<Object> addProblemSummaryAll(ProblemSummaryInfo problemSummaryInfo) {
        try {
            String projectName = problemSummaryInfo.getProjectName();
            String projectCategory = problemSummaryInfo.getProjectCategory();
            List<Object> tasks = problemSummaryInfo.getTasks();
            if (StrUtil.isBlank(projectName) || StrUtil.isBlank(projectCategory)){
                return Answer.error("项目名称和项目分类不能为空");
            }
            if (CollectionUtil.isEmpty(tasks)){
                return Answer.error("任务不能为空");
            }
            problemSummaryInfo.setStatus("1");
//            problemSummaryInfoMapper.insert(problemSummaryInfo);
            Answer<Object> objectAnswer = addProblemSummaryInfo(problemSummaryInfo);
            if (objectAnswer.getCode() != 200){
                return Answer.error(objectAnswer.getMsg());
            }
            Integer id = Convert.toInt(objectAnswer.getResult());
            for (int i = 0; i < tasks.size(); i++) {
                JSONObject task = JSON.parseObject(JSON.toJSONString(tasks.get(i)));
                String taskName = task.getString("name");
                String taskContent = task.getString("content");
                JSONArray task1Array = task.getJSONArray("children");
                if (StrUtil.isBlank(taskName) || StrUtil.isBlank(taskContent)){
                    return Answer.error("任务名称、任务内容不能为空");
                }
                TaskInfo taskInfo = new TaskInfo();
                taskInfo.setSummaryId(id);
                taskInfo.setName(taskName);
                taskInfo.setContent(taskContent);
                taskInfo.setSort(i);
                taskInfo.setState("1");
                taskInfo.setCreateTime(new Date());
                taskInfoMapper.insert(taskInfo);
                Integer id1 = taskInfo.getId();
                if(CollectionUtil.isNotEmpty(task1Array)){
                    for (int i1 = 0; i1 < task1Array.size(); i1++) {
                        JSONObject task1 = JSON.parseObject(JSON.toJSONString(task1Array.get(i1)));
                        String taskName1 = task1.getString("name");
                        String taskContent1 = task1.getString("content");
                        JSONArray task2Array = task1.getJSONArray("children");
                        if (StrUtil.isBlank(taskName) || StrUtil.isBlank(taskContent1)){
                            return Answer.error("任务名称、任务内容不能为空");
                        }
                        Task1Info task1Info = new Task1Info();
                        task1Info.setTaskId(id1);
                        task1Info.setName(taskName1);
                        task1Info.setContent(taskContent1);
                        task1Info.setSort(i);
                        task1Info.setState("1");
                        task1Info.setCreateTime(new Date());
                        task1InfoMapper.insert(task1Info);
                        Integer id2 = task1Info.getId();
                        if(CollectionUtil.isNotEmpty(task2Array)){
                            for (int i2 = 0; i2 < task2Array.size(); i2++) {
                                JSONObject task2 = JSON.parseObject(JSON.toJSONString(task2Array.get(i2)));
                                String taskName2 = task2.getString("name");
                                String taskContent2 = task2.getString("content");
                                if (StrUtil.isBlank(taskName) || StrUtil.isBlank(taskContent2)){
                                    return Answer.error("任务名称、任务类型不能为空");
                                }
                                Task2Info task2Info = new Task2Info();
                                 task2Info.setTask1Id(id2);
                                task2Info.setName(taskName2);
                                task2Info.setContent(taskContent2);
                                task2Info.setSort(i);
                                task2Info.setState("1");
                                task2Info.setCreateTime(new Date());
                                task2InfoMapper.insert(task2Info);
                            }
                        }
                    }
                }
            }

            return Answer.ok("添加成功");
        } catch (Exception e) {
            e.printStackTrace();
            return LOG.error(Answer.build(), "请求addProblemSummaryAll失败！", e);
        }
    }

    @Override
    public Answer<Object> queryProblemSummaryAll(ProblemSummaryInfo problemSummaryInfo) {
        try{
            JSONObject resJson = new JSONObject();
            Integer id = problemSummaryInfo.getId();
            if (id == null){
                return Answer.error("id不能为空");
            }
            ProblemSummaryInfo problemSummaryInfoRes = problemSummaryInfoMapper.selectById(id);
            if (problemSummaryInfoRes == null){
                return Answer.error("数据不存在");
            }
            List<TaskInfo> taskInfos = taskInfoMapper.selectList(new LambdaQueryWrapper<TaskInfo>().eq(TaskInfo::getSummaryId, id));
            if (CollectionUtil.isNotEmpty(taskInfos)) {
                for (TaskInfo taskInfo : taskInfos) {
                    List<Task1Info> task1Infos = task1InfoMapper.selectList(new LambdaQueryWrapper<Task1Info>().eq(Task1Info::getTaskId, taskInfo.getId()));
                    if (CollectionUtil.isNotEmpty(task1Infos)) {
                        for (Task1Info task1Info : task1Infos) {
                            List<Task2Info> task2Infos = task2InfoMapper.selectList(new LambdaQueryWrapper<Task2Info>().eq(Task2Info::getTask1Id, task1Info.getId()));
                            task1Info.setChildren(task2Infos);
                        }
                    }
                    taskInfo.setChildren(task1Infos);
                }
                resJson.put("tasks",taskInfos);
                resJson.put("projectName",problemSummaryInfoRes.getProjectName());
                resJson.put("projectCategory",problemSummaryInfoRes.getProjectCategory());
                resJson.put("summaryId",problemSummaryInfoRes.getId());
            }
            return Answer.ok(resJson);
        } catch (Exception e) {
            e.printStackTrace();
            return LOG.error(Answer.build(), "请求queryProblemSummaryAll失败！", e);
        }
    }

    @Override
    public Answer<Object> queryProblemSummaryTree() {
        try {
            List<JSONObject> resList = CollectionUtil.newArrayList();
            List<ProblemSummaryInfo> problemSummaryInfoRes = problemSummaryInfoMapper.selectList(null);
            if (problemSummaryInfoRes == null) {
                return Answer.error("数据不存在");
            }
            for (ProblemSummaryInfo problemSummaryInfo : problemSummaryInfoRes) {
                JSONObject resJson = new JSONObject();
                Integer id = problemSummaryInfo.getId();
                List<TaskInfo> taskInfos = taskInfoMapper.selectList(new LambdaQueryWrapper<TaskInfo>().eq(TaskInfo::getSummaryId, id));
                if (CollectionUtil.isNotEmpty(taskInfos)) {
                    for (TaskInfo taskInfo : taskInfos) {
                        List<Task1Info> task1Infos = task1InfoMapper.selectList(new LambdaQueryWrapper<Task1Info>().eq(Task1Info::getTaskId, taskInfo.getId()));
                        if (CollectionUtil.isNotEmpty(task1Infos)) {
                            for (Task1Info task1Info : task1Infos) {
                                List<Task2Info> task2Infos = task2InfoMapper.selectList(new LambdaQueryWrapper<Task2Info>().eq(Task2Info::getTask1Id, task1Info.getId()));
                                task1Info.setChildren(task2Infos);
                            }
                        }
                        taskInfo.setChildren(task1Infos);
                    }
                    resJson.put("tasks", taskInfos);
                    resJson.put("projectName", problemSummaryInfo.getProjectName());
                    resJson.put("projectCategory", problemSummaryInfo.getProjectCategory());
                    resJson.put("summaryId", problemSummaryInfo.getId());
                    resList.add(resJson);
                }
            }
            return Answer.ok(resList);
        } catch (Exception e) {
            e.printStackTrace();
            return LOG.error(Answer.build(), "请求queryProblemSummaryAll失败！", e);
        }
    }
}
